import { get_menus } from '@/api/api.js'
import { defineStore } from 'pinia'
import { formatRoutesByAPI, formatAuthByResource } from '@/utils'
import router from '@/router/index'
import { emitter } from '@/utils/bus.js'
import { ref } from 'vue'
import { sessionMemory } from '@/utils/sessionMemory'
import { ElMessage, ElMessageBox } from 'element-plus'
import _ from 'lodash-es'


const nameMap = {}


export const useRouterStore = defineStore(
  'router',
  () => {
    const authBtn = ref(sessionMemory.getItem('authBtn')) // 前端按钮鉴权集合
    const keepAliveRouters = ref()
    const keepAliveRoutersArr = ref([])// 被缓存的路由名称
    const asyncRouterFlag = ref(0) // 添加flag防止多次获取动态路由和栈溢出
    const asyncRouters = ref({
      allRoutes: [],
      leftRoutes: [],
    })
    const KeepAliveFilter = routes => {
      keepAliveRoutersArr.value = []
      const getAliveRoutes = routes => {
        routes &&
          routes.forEach(item => {
            // 子菜单中有 keep-alive 的，父菜单也必须 keep-alive，否则无效。这里将子菜单中有 keep-alive 的父菜单也加入。
            // item.children && item.children.some(ch => ch.meta.keepAlive)) ||
            if (item.meta.keepAlive) {
              keepAliveRoutersArr.value.push(item.name)
              nameMap[item.name] = item.name
            }
            if (item.children && item.children.length > 0) {
              getAliveRoutes(item.children)
            }
          })
      }
      getAliveRoutes(routes)
    }
    

    const setAuthBtn = val => {
      const res = formatAuthByResource(val)
      authBtn.value = res
      sessionMemory.setItem("authBtn", res)
    }


    const setKeepAliveRouters = (history) => {
      const keepArrTemp = []
      history.forEach(item => {
        if (nameMap[item.name]) {
          keepArrTemp.push(nameMap[item.name])
        }
      })
      keepAliveRouters.value = Array.from(new Set(keepArrTemp))
    }
    emitter.on('setKeepAlive', setKeepAliveRouters)

    const clearRouter = () => {
      authBtn.value = []
      asyncRouters.value.allRoutes = []
      asyncRouters.value.leftRoutes = []
    }

    const routeMap = {}
    // 从后台获取动态路由
    const SetAsyncRouter = async () => {
      asyncRouterFlag.value++
      const baseRouter = [
        {
          path: '/layout',
          code: '/layout',
          name: 'layout',
          type: 1,
          component: '/layout/index.vue',
          meta: {
            title: '底层layout',
            keepAlive: false
          },
          children: []
        }
      ]
      const baseRouter2 = [
        {
          path: '/layout',
          code: '/layout',
          name: 'layout',
          type: 1,
          component: '/layout/index.vue',
          meta: {
            title: '底层layout',
            keepAlive: false
          },
          children: []
        }
      ]
      asyncRouters.value.allRoutes = []
      asyncRouters.value.leftRoutes = []
      const res = await get_menus()
      // const res = apiResult // 模拟接口获取路由
      // res.data.push(apiResult.data[0])
      if (res.succeed) {
        if (res.data && res.data.length > 0) {
          // 处理按钮鉴权字符
          setAuthBtn(res.data)
          const asyncRouter = res.data
          asyncRouter && asyncRouter.push({
            code: 'Reload',
            isDisplayInMainMenu: 0,
            name: 'Reload',
            meta: {
              title: '',
              closeTab: true,
            },
            component: '/error/reload'
          })
          baseRouter[0].children = asyncRouter
          const formatRoutes = formatRoutesByAPI(baseRouter) // 处理菜单格式
          // 处理全屏菜单-start
          let i = formatRoutes[0].children.findIndex(item => {
            return item.isFullScreen == '1'
          })
          if (formatRoutes[0].children[i]) {
            formatRoutes.push(_.cloneDeep(formatRoutes[0].children[i]))
            // 保留原始全屏菜单
            formatRoutes[0].children[i].path = formatRoutes[0].children[i].path.replace('/', '')
          }
      
          // 处理全屏菜单-end
          let currentRoutes = formatRoutes
          baseRouter2[0].children = currentRoutes[0].children.length > 0 ? currentRoutes[0].children : [currentRoutes[0]] // 左侧菜单
          asyncRouters.value.allRoutes = formatRoutes // 总菜单
          asyncRouters.value.leftRoutes = baseRouter2 // 左侧菜单
          KeepAliveFilter(formatRoutes)
          return true
        } else {
          ElMessage({
            showClose: true,
            message: '请联系管理员给该账号分配角色并配置菜单！',
            type: 'error'
          })
          sessionStorage.clear()
          router.push({ name: 'Login', replace: true })
          return false
        }
      } else {
        return false
      }
    }

    // 清除某个路由的缓存
    const clearKeepAliveRouter = name => {
      const index = keepAliveRoutersArr.value.indexOf(name)
      if (index > -1) {
        keepAliveRoutersArr.value.splice(index, 1)
      }
    }
    // 添加某个路由缓存
    const addKeeyAliveRouter = name => {
      const index = keepAliveRoutersArr.value.indexOf(name)
      if (index < 0) {
        keepAliveRoutersArr.value.push(name)
      }
    }
    return {
      authBtn,
      clearRouter,
      asyncRouters,
      keepAliveRouters,
      keepAliveRoutersArr,
      clearKeepAliveRouter,
      addKeeyAliveRouter,
      asyncRouterFlag,
      SetAsyncRouter,
      routeMap
    }
  },
  // 数据持久化
  {
    persist: {
      enabled: false,
      strategies: [
        { storage: sessionStorage, paths: ['asyncRouters'], key: 'asyncRouters' }
      ]
    }
  }
)
